﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel.Activation;
using System.Collections.ObjectModel;
using System.Web;
using System.IO;
using ServeurRSS_1_0.Source.Model;

namespace ServeurRSS_1_0
{

   
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service_UserManagement" in code, svc and config file together.
    [AspNetCompatibilityRequirements(
                 RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service_UserManagement : SessionManagerService, IServiceUserManagement
    {
 

        public Service_UserManagement()
        {
            this.TryingAuthenticateUser = authenticateUser;
        }
        
        private DirectoryModel modelDirectory;
        private DirectoryModel ModelDirectory
        {
            get
            { 
                if (modelDirectory == null)
                    return new DirectoryModel();
                return modelDirectory;
            }
            set
            {
                if (modelDirectory != value)
                    modelDirectory = value;
            }
        }

        private UserModel modelUser;
        private UserModel ModelUser
        {
            get
            {
                if (modelUser == null)
                    return new UserModel();
                return modelUser;
            }
            set
            {
                if (modelUser != value)
                    modelUser = value;
            }
        }

        #region UserManagement
        public string registerUser(DataUser duser)
        {
            User user = ModelUser.getUserFromData(duser);
            try
            {
                string result = "OK";
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();

                var users = from elements in db.Users
                            where  elements.email == user.email
                            select elements;

                if (users.Count() > 0)
                    result = "L'adresse mail est déjà utilisé";
                else
                {
                    user.creation_date = DateTime.Now;
                    user.id = Guid.NewGuid();
                    db.Users.InsertOnSubmit(user);
                    db.SubmitChanges();

                    ModelDirectory.createDirectory(user.id, "Root");
                    DataDirectory tmp  = ModelDirectory.getDataDirectory( ModelDirectory.getRootDirectoryForUser(user.id));
                    ModelDirectory.createDirectory(user.id, "Favoris", tmp);
                }
                return result;
            }
            catch (Exception ex)
            {
                //System.IO.File.WriteAllText("D:\\epitech\\ASP.NET\\Serveur\\Logs", "Erreur lors de l'enregistrement : " + ex.Message);

                return "Erreur lors de l'enregistrement : " + ex.Message;
            }
        }

        public string checkMail(string mail)
        {

            try
            {
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();

                User user = db.Users.SingleOrDefault(p => p.email == mail);
                if (user != null)
                    return "Cette email est déjà utilisé!";
                else
                    return "OK";

            }
            catch (Exception ex)
            {
                return "Erreur email : " + ex.Message;
            }
        }

       //TODO devra retourner le user ou au moins id du user
        public DataUser authenticateUser(DataUser duser)
        {
            DataUser defaultUser = new DataUser();
            defaultUser.name = "Erreur => ";
            User user = ModelUser.getUserFromData(duser);
            try
            {
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();
                User res = db.Users.SingleOrDefault(p => p.email == user.email && p.password == user.password);
                if (res != null /*&& (res.connection_state == false || res.connection_state == null)*/)
                {
                    res.connection_state = true;
                    db.SubmitChanges();
                    HttpContext.Current.Session.Add("idUser", res.id);
                    return ModelUser.getDataUser(res);
                }
                throw (new Exception(res == null ? "resultat linq == null" : "connectionState == true for res.name = *" + res.login + "*"));
            }
            catch (Exception ex)
            {
                throw new Exception("Exception catch message : \r\n" + ex.Message, ex.InnerException);
            }
        }

        public bool updateUser(DataUser duser)
        {
            User user = ModelUser.getUserFromData(duser);
            try
            {
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();
                User updateduser = db.Users.Single(c => c.id == user.id);
                if (user.login != null && user.login.Length > 3)
                    updateduser.login = user.login;
                if (user.password != null && user.password.Length >= 4)
                    updateduser.password = user.password;
                if (user.email != null)
                    updateduser.email = user.email;
                db.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        // Returns the user's profile
        public DataUser getUserProfileById(System.Guid userid)
        {
            try
            {
                User retuser = new User();
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();

                var auser = from elem in db.Users
                            where elem.id == userid
                            select elem;

                retuser = auser.FirstOrDefault<User>();
                return ModelUser.getDataUser(retuser);
            }
            catch (Exception ex)
            {

                return null;
            }
        }

        // Returns the user's profile
        public DataUser getUserProfileByLogin(String login)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated == false)
                return null;
            try
            {
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();
                User retuser = new User();

                var auser = from elem in db.Users
                            where elem.email == login
                            select elem;

                retuser = auser.FirstOrDefault<User>();
                return ModelUser.getDataUser(retuser);
            }
            catch (Exception ex)
            {
                return new DataUser
                {
                    name = "Erreur login Exception" + ex.Message
                };
            }
        }
      
        //TODO creer une classe parent session qui va gérer les droit d'admissions aux methodes.
        public string eraseUser(System.Guid userid, string loginToErase)
        {
            try
            {
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();
                User user = db.Users.SingleOrDefault(u => u.id == userid);
                if (user == null)
                    return "NOK you are unknown";
                if (user.statut != 1)
                    return "Vous n'avez pas les droits pour supprimer une personne";
                User userToErase = db.Users.SingleOrDefault(u => u.id == userid);
                db.Users.DeleteOnSubmit(userToErase);
                db.SubmitChanges();
                return "OK";
            }
            catch (Exception ex)
            {
                return "Erreur lors de l'action de supression de " + loginToErase;
            }
}

        public string checkLogin(string login)
        {
            try
            {
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();

                User user = db.Users.SingleOrDefault(p => p.login == login);
                if (user != null)
                    return "Ce login est déjà utilisé!";
                else
                    return "OK";

            }
            catch (Exception ex)
            {
                return "Erreur login : " + ex.Message;
            }
        }

        public List<DataUser> getListOfUser()
        {
            try
            {
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();
                List<DataUser> res = ModelUser.getListFromUser(db.Users.Select(p => p).ToList());
                return res;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }

        public string closeSession(string login)
        {
            try
            {
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();

                User user = db.Users.SingleOrDefault(p => p.login == login);
                if (user != null)
                {
                    user.connection_state = false;
                    db.SubmitChanges();
                    return "OK";
                }
                return "user not found";
            }
            catch (Exception ex)
            {
                return "Erreur login : " + ex.Message;
            }
        }

        #endregion

        public bool isServerAvailable()
        {
            return true;
        }
    }

   

 }
